<script setup>
import { ref } from 'vue';
import { useAppUserStore, useAppMenuStore } from '@/stores';
import { useRouter } from 'vue-router';
import { User, Lock } from '@element-plus/icons-vue';
import {
  appUserLoginService,
  appUserCAPTCHARefreshService
} from '@/apis/appuser';

import { baseURL } from '@/utilities/request';

const isShowCaptcha = ref(false);
const captchaImgUrl = ref('');

const refreshCAPTACHA = async () => {
  let res = await appUserCAPTCHARefreshService();
  captchaImgUrl.value = res.data;
  ElMessage.success('验证码刷新成功');
};

const loginFormDefault = {
  userName: '',
  password: '',
  requestId: '',
  captchaCode: '',
  isRememberMe: false
};

const loginFormModel = ref({
  ...loginFormDefault
});

const loginForm = ref();

const appUserStore = useAppUserStore();
const appMenuStore = useAppMenuStore();
const router = useRouter();
const login = async () => {
  await loginForm.value.validate();
  const res = await appUserLoginService(loginFormModel.value);
  if (res.success) {
    // 登录成功
    appUserStore.setTokenObj(res.data);
    await appMenuStore.refreshAppMenus();
    ElMessage.success('登录成功');
    await router.push('/');
  } else {
    // 登录失败
    ElMessage.error(res.msg);
    if (res.data) {
      loginFormModel.value.requestId = '';
      isShowCaptcha.value = true;
      captchaImgUrl.value = `${baseURL}${res.data}`;
    }
  }
};

const emits = defineEmits(['switchToRegister', 'switchToForgetPasswd']);
const switchToRegister = () => {
  emits('switchToRegister');
};

const switchToForgetPasswd = () => {
  emits('switchToForgetPasswd');
};

const rules = {
  userName: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 5, max: 10, message: '用户名必须是 5-10 位的字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    {
      pattern: /^\S{6,15}$/,
      message: '密码必须是 6-15 位的非空字符',
      trigger: 'blur'
    }
  ],
  captchaCode: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
};

const resetLogin = () => {
  loginFormModel.value = ref({
    ...loginFormDefault
  });
};

defineExpose({
  resetLogin
});
</script>

<template>
  <!--登录相关表单-->
  <el-form
    :model="loginFormModel"
    :rules="rules"
    ref="loginForm"
    size="large"
    autocomplete="off"
  >
    <el-form-item>
      <h1>登录</h1>
    </el-form-item>
    <el-form-item prop="userName">
      <el-input
        v-model="loginFormModel.userName"
        :prefix-icon="User"
        placeholder="请输入用户名"
      ></el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input
        v-model="loginFormModel.password"
        :prefix-icon="Lock"
        type="password"
        show-password
        placeholder="请输入密码"
      ></el-input>
    </el-form-item>
    <el-form-item
      prop="captchaCode"
      class="captcha-container"
      v-if="isShowCaptcha"
    >
      <el-input
        v-model="loginFormModel.captchaCode"
        type="text"
        placeholder="验证码"
      ></el-input>
      <a @click="refreshCAPTACHA()">
        <img class="captcha-img" :src="captchaImgUrl" />
      </a>
    </el-form-item>
    <el-form-item>
      <div class="extra-opt">
        <el-checkbox v-model="loginFormModel.isRememberMe">记住我</el-checkbox>
        <el-link
          type="primary"
          :underline="false"
          @click="switchToForgetPasswd"
        >
          忘记密码？
        </el-link>
      </div>
    </el-form-item>
    <el-form-item>
      <el-button @click="login" class="button" type="primary" auto-insert-space>
        登录
      </el-button>
    </el-form-item>
    <el-form-item class="extra-opt">
      <el-link type="info" :underline="false" @click="switchToRegister()">
        注册 →
      </el-link>
    </el-form-item>
  </el-form>
</template>
<style lang="scss" scoped>
.button {
  width: 100%;
}

.extra-opt {
  width: 100%;
  display: flex;
  justify-content: space-between;
}

.captcha-container :deep(.el-form-item__content) {
  flex-wrap: nowrap;
  justify-content: space-between;
}

.captcha-img {
  flex-basis: 100px;
  margin-left: 30px;
}
</style>
